﻿using Castle.MicroKernel.Registration;
using MRSite.Common.Dependency;
using MRSite.Common.Kernels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MRSite.Common
{
    public class Startup : IDisposable
    {
        private Startup(Type launchKernel, IContainerManager ctnManager)
        {
            this.launchKernel = launchKernel;
            this.ctnManager = ctnManager;

        }

        public static Startup Launch<T>(IContainerManager ctnManager)
            where T : BaseKernel
        {
            return new Startup(typeof(T), ctnManager);
        }

        public void Initialize()
        {
            try
            {
                RegistInstance();
                ctnManager.Container.Install(new CommonInstaller());
                var manager = ctnManager.Resolver<IKernelManager>();
                manager.Initialize(launchKernel);
                manager.StartAll();
            }
            catch (Exception e)
            {
                //_logger.Fatal(e.Message, e);
                throw e;
            }

        }

        private void RegistInstance()
        {
            if (!ctnManager.IsRegisted<Startup>())
            {
                ctnManager.Container.Register(
                    Component.For<Startup>().Instance(this)
                    );
            }
        }

        public void Dispose()
        {
            if (IsDisposed)
            {
                return;
            }
            IsDisposed = true;
        }
        private Type launchKernel;
        private IContainerManager ctnManager;
        private bool IsDisposed;
    }
}
